﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using EQT.Model;
using EQT.Dal;
using System.Collections.Generic;

public partial class TestItem : System.Web.UI.Page
{
    private DaTestCatalog daCatalog = new DaTestCatalog();
    private DaTestItem daItem = new DaTestItem();
    private DaDept dalDept = new DaDept();
    private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    private UserContext context;

    protected void Page_Load(object sender, EventArgs e)
    {
        context = Session["USER_CONTEXT"] as UserContext;
        AspNetPager1.PageSize = 8;
        divResult.Visible = false;
        OperationResult.Text = "";

        if (!Page.IsPostBack)
        {
            DataSet dsDept = dalDept.Query(string.Empty);

            Utility.BindDataSet2Combox(dsDept, ddlItemAddDept, "Dept_Name", "Dept_ID");
            Utility.BindDataSet2Combox(dsDept, ddlItemEidtDept, "Dept_Name", "Dept_ID");
            
            BindDirTree();

            if (Request.QueryString["rtnctgid"]!=null&&!string.IsNullOrEmpty(Request.QueryString["rtnctgid"].ToString()))
            {
                foreach (TreeNode tn in testCatalogTreeView.Nodes)
                {
                    TreeNode rtn=this.SearchNode(tn, Request.QueryString["rtnctgid"].ToString()) ;
                    if (rtn != null)
                    {
                        rtn.Select();
                        catalogTreeView_SelectedNodeChanged(tn, null);
                        break;
                    }
                }
            }
            if (Request.QueryString["pageindex"] != null && !string.IsNullOrEmpty(Request.QueryString["pageindex"].ToString()))
            {
                AspNetPager1.CurrentPageIndex = int.Parse(Request.QueryString["pageindex"].ToString());
                BindItemsDgv(testCatalogTreeView.SelectedNode.Value, false);
            }
            
            if (Request.QueryString["rtnitemid"] != null && !string.IsNullOrEmpty(Request.QueryString["rtnitemid"].ToString()))
            {
                foreach (GridViewRow gvr in GridViewTestItem.Rows)
                {
                    if (gvr.Cells[0].Text == Request.QueryString["rtnitemid"].ToString())
                    {
                        LinkButton link = gvr.FindControl("lbDetailItem") as LinkButton;
                        if (link != null)
                        {
                            lbDetailItem_Click(link, null);
                        }
                    }
                }
            }
        }
    }

    private TreeNode SearchNode(TreeNode tnParent,string keyvalue)
    {
        if (tnParent.ChildNodes.Count > 0)
        {
            foreach (TreeNode tn in tnParent.ChildNodes)
            {
                TreeNode rtn=this.SearchNode(tn, keyvalue);
                if(rtn!=null)
                {
                    return rtn;
                }
            }
        }
        else
        {
            if (tnParent.Value == keyvalue)
            {
                return tnParent;
            }
        }
        return null;
    }

    private void BindDirTree()
    {
        testCatalogTreeView.Nodes.Clear();
        IList<MoTestCatalog> listRoot = daCatalog.GetEntities(" WHERE tc_flag='R'");
        for (int i = 0; i < listRoot.Count; i++)
        {
            TreeNode tnRoot = new TreeNode(listRoot[i].TestCtgName, listRoot[i].TestCtgId);

            this.BindSubNode(tnRoot, listRoot[i].TestCtgId);

            testCatalogTreeView.Nodes.Add(tnRoot);
        }
        testCatalogTreeView.ExpandAll();
    }

    private void BindSubNode(TreeNode tnParent, string id)
    {
        DataSet ds = daCatalog.GetCatalogTreeDs(id);
        if (ds.Tables[0].Rows.Count == 0)
            return;

        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            TreeNode tn = new TreeNode(ds.Tables[0].Rows[i]["Test_Ctg_Name"].ToString(), ds.Tables[0].Rows[i]["Test_Ctg_ID"].ToString());
            BindSubNode(tn, ds.Tables[0].Rows[i]["Test_Ctg_ID"].ToString());
            tnParent.ChildNodes.Add(tn);
        }
    }

    protected void AspNetPager1_PageChanged(object sender, EventArgs e)
    {
        if (sender == null && e == null) return;

        BindItemsDgv(testCatalogTreeView.SelectedNode.Value,false);
    }

    /// <summary>
    /// 绑定数据到GridView
    /// </summary>
    /// <param name="item_id">检验项编号</param>
    /// <param name="flag">是否重新绑定，false表示从原来的页码开始绑定，true表示从第一页开始。</param>
    private void BindItemsDgv(string item_id,bool flag)
    {
        int count = 0;
        string strSQL = "select * from V_TEST_ITEM  where Parent_Ctg_ID='" + item_id + "' and tc_flag='I'";

        if (flag)
        {
            AspNetPager1.CurrentPageIndex = 0;
        }

        GridViewTestItem.DataSource = DaCommon.GetPaginationData(strSQL, AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex - 1, " Test_Ctg_ID desc", out count);
        GridViewTestItem.DataBind();
        AspNetPager1.RecordCount = count;
        if (count == 0)
        {
            divResult.Visible = true;
            OperationResult.Text = "该目录下无文件";
        }
        else
        {
            divResult.Visible = false ;
            OperationResult.Text = "";
        }
    }

    protected void btnAddCatalog_Click(object sender, EventArgs e)
    {
        if (testCatalogTreeView.SelectedNode != null)
        {
            txtSubCatalog.Text = "";
            txtSubCatalogMemo.Text = "";

            this.ModalPopupExtenderAddCatalog.Show();
        }
        else
        {
            divResult.Visible = true;
            OperationResult.Text = "请选择检验目录!";
        }
    }

    protected void catalogTreeView_SelectedNodeChanged(object sender, EventArgs e)
    {
        //AspNetPager1.CurrentPageIndex = 0;
        if (testCatalogTreeView.SelectedNode != null)
        {
            AspNetPager1.CurrentPageIndex = 0;
            //BindItemsDgv(testCatalogTreeView.SelectedNode.Value,false);
            lbCurrentCatalog.Text = testCatalogTreeView.SelectedNode.Text;
            labNowCatalog.Text = testCatalogTreeView.SelectedNode.Text;
            btnCreateTemplate.Visible = false;
            RepTemplate.DataSource = null;
            RepTemplate.DataBind();
            labNowItem.Text = "";
            labMemo.Text = "";
        }
        else
        {
            divResult.Visible = true;
            OperationResult.Text = "您未选择任何目录！";
        }
    }

    protected void btnRemoveCatalog_Click(object sender, EventArgs e)
    {
        if (testCatalogTreeView.SelectedNode != null)
        {
            lbCatalogToDelInfo.Text = String.Format("您将要删除 {0} 目录！", testCatalogTreeView.SelectedNode.Text);
            this.ModalPopupExtenderDelCatalog.Show();
        }
    }

    ///// <summary>
    ///// 删除检验项
    ///// </summary>
    ///// <param name="sender"></param>
    ///// <param name="e"></param>
    //protected void GvDelete_Click(object sender, EventArgs e)
    //{
    //    LinkButton btn = sender as LinkButton;
    //    GridViewRow gvr = (GridViewRow)btn.NamingContainer;
    //    string item_id = (string)GridViewTestItem.DataKeys[gvr.RowIndex].Value;

    //    try
    //    {
    //        int rtn=daCatalog.DeleteCatalogAndItems(item_id);
    //        if (rtn == 1)
    //        {
    //            divResult.Visible = true;
    //            OperationResult.Text = "删除检验项成功!";
    //            BindItemsDgv(testCatalogTreeView.SelectedNode.Value,false);
    //            return;
    //        }
    //        else if (rtn == 2)
    //        {
    //            divResult.Visible = true;
    //            OperationResult.Text = "该检验目录存在子项目,请先删除自项目!";
    //            return;
    //        }
    //        else
    //        {
    //            divResult.Visible = true;
    //            OperationResult.Text = "删除检验项失败!";
    //            return;
    //        }

            
    //    }
    //    catch (Exception ex)
    //    {
    //        log.Error(ex);
    //        divResult.Visible = true;
    //        OperationResult.Text = "删除检验项发生错误!";
    //    }

    //}

    /// <summary>
    /// 删除检验项目录
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnDelCatalog_OK(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(testCatalogTreeView.SelectedValue))
        {
            divResult.Visible = true;
            OperationResult.Text = "请选择要删除的检验项分类!";
            return;
        }
        try
        {
            if (daCatalog.DeleteCatalogAndItems(testCatalogTreeView.SelectedValue) == 2)
            {
                divResult.Visible = true;
                OperationResult.Text = "该检验项目录存在子结点,请删除子结点后再删除该检验项目录!";
            }
            else
            {
                divResult.Visible = true;
                OperationResult.Text = "检验项目录删除成功!";
                BindDirTree();
                lbCatalogToDelInfo.Text = String.Empty;
            }
            this.ModalPopupExtenderDelCatalog.Hide();
        }
        catch (DalException de)
        {
            divResult.Visible = true;
            OperationResult.Text = "删除检验项目录发生异常!";
            Utility.GlobalLog.Warn("删除检验项目录发生异常", de);
            lbCatalogToDelInfo.Text = String.Format("删除目录 {0} 失败！因为该目录不为空！", testCatalogTreeView.SelectedNode.Text);
        }
    }

    protected void btnAddCatalogOK_Click(object sender, EventArgs e)
    {
        
        if (string.IsNullOrEmpty(txtSubCatalog.Text.Trim()))
        {
            divResult.Visible = true;
            OperationResult.Text = "请输入完整信息!检验项分类名称不能为空!";
            return;
        }
        if (string.IsNullOrEmpty(testCatalogTreeView.SelectedValue))
        {
            divResult.Visible = true;
            OperationResult.Text = "请选择上级检验项分类!";
            return;
        }

        MoTestCatalog modf = new MoTestCatalog();
        modf.CreateTime = DateTime.Now;
        modf.ParentCtgId = testCatalogTreeView.SelectedValue;
        modf.Rem=txtSubCatalogMemo.Text.Trim();
        modf.TcFlag = "D";
        modf.TestCtgId=SequenceKeys.GenerateTestCatalogID();
        modf.TestCtgName=txtSubCatalog.Text.Trim();
        modf.UpdateTime=modf.CreateTime;
        try
        {
            daCatalog.Add(modf);
            BindDirTree();
            this.ModalPopupExtenderAddCatalog.Hide();

            divResult.Visible = true;
            OperationResult.Text = "新建检验项分类保存成功!";
        }
        catch (Exception ex)
        {
            divResult.Visible = true;
            OperationResult.Text = "保存新检验项分类失败!";
            log.Error(ex);
        }
    }
   
    protected void lbEditItem_Click(object sender, EventArgs e)
    {
        LinkButton btn = sender as LinkButton;
        GridViewRow gvr = (GridViewRow)btn.NamingContainer;
        string item_id = (string)GridViewTestItem.DataKeys[gvr.RowIndex].Value;
        MoTestCatalog mod = daCatalog.GetEntity(item_id);
        MoTestItem moditem = daItem.GetEntity(item_id);
        if (mod != null&&moditem!=null)
        {
            labItemEditID.Text = mod.TestCtgId;
            txtItemEidtName.Text = mod.TestCtgName;
            txtItemEidtMemo.Text = mod.Rem;
            ddlItemEidtDept.SelectedValue = moditem.Dept_Id;
            ddlItemEidtStatus.SelectedValue = moditem.Ability_Status.ToString();
            txtItemEidtParameter.Text = moditem.Test_Parameters;
            txtItemEidtPrice.Text = moditem.Price.ToString();
            mpeItemEdit.Show();
        }
        else
        {
            divResult.Visible = true;
            OperationResult.Text = "未检索到该检验项信息,请检查!";
            return;
        }
    }

    protected void lbDetailItem_Click(object sender, EventArgs e)
    {
        LinkButton btn = sender as LinkButton;
        GridViewRow gvr = (GridViewRow)btn.NamingContainer;
        string item_id = (string)GridViewTestItem.DataKeys[gvr.RowIndex].Value;
        btnCreateTemplate.CommandName = item_id;
        btnCreateTemplate.Visible = true;
        labNowItem.Text = gvr.Cells[1].Text.Trim();
        ViewState["ITEMID"] = item_id;
        MoTestCatalog mod=daCatalog.GetEntity(item_id);
        if(mod!=null)
        {
            labMemo.Text =mod.Rem;
        }
        else
        {
            labMemo.Text = "";
        }
        this.BindTemplateRepeater(item_id);
    }

    protected void lbDelItem_Click(object sender, EventArgs e)
    {
        LinkButton btn = sender as LinkButton;
        GridViewRow gvr = (GridViewRow)btn.NamingContainer;
        string item_id = (string)GridViewTestItem.DataKeys[gvr.RowIndex].Value;
        
        try
        {

            if (daItem.DeleteTestItem(item_id))
            {
                divResult.Visible = true;
                if (GridViewTestItem.Rows.Count == 1)
                {
                    BindItemsDgv(testCatalogTreeView.SelectedNode.Value, false);
                }
                else
                {
                    BindItemsDgv(testCatalogTreeView.SelectedNode.Value, true);
                }
                OperationResult.Text = "检验项删除成功!";
            }
            else
            {
                divResult.Visible = true;
                OperationResult.Text = "检验项删除失败!";
            }
        }
        catch(Exception ex)
        {
            Utility.GlobalLog.Error("删除检验项异常",ex);
            divResult.Visible = true;
            OperationResult.Text = "删除检验项发生异常!该检验项已被使用。";
        }
    }

    protected void btnCreateItem_Click(object sender, EventArgs e)
    {
        if (testCatalogTreeView.SelectedNode != null)
        {
            labItemAddCatalog.Text = testCatalogTreeView.SelectedNode.Text;
            txtItemAddMemo.Text = "";
            txtItemAddName.Text = "";
            txtItemAddParameter.Text = "";
            txtItemAddPrice.Text = "";
            mpeItemAdd.Show();
        }
        else
        {
            divResult.Visible = true;
            OperationResult.Text = "请选择检验目录!";
        }
    }

    protected void BtnEditCatalog_Click(object sender, EventArgs e)
    {
        if (testCatalogTreeView.SelectedNode != null)
        {
            MoTestCatalog mod = daCatalog.GetEntity(testCatalogTreeView.SelectedValue);
            txtEditCatalogMemo.Text = mod.Rem;
            txtEditCatalogName.Text = mod.TestCtgName;
            labEditCatalogID.Text = mod.TestCtgId;
            ModalPopupExtenderEditCatalog.Show();
        }
        else
        {
            divResult.Visible = true;
            OperationResult.Text = "请选择检验目录!";
        }
    }

    protected void btnEditCatalogSave_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(txtEditCatalogName.Text.Trim()))
        {
            divResult.Visible = true;
            OperationResult.Text = "请输入完整信息!检验项分类名称不能为空!";
            return;
        }
        MoTestCatalog mod = daCatalog.GetEntity(labEditCatalogID.Text);
        if (mod != null)
        {
            mod.TestCtgName = txtEditCatalogName.Text;
            mod.Rem = txtEditCatalogMemo.Text;
            mod.UpdateTime = DateTime.Now;
        }
        try
        {
            if (daCatalog.Update(mod) == 1)
            {
                divResult.Visible = true;
                OperationResult.Text = "修改检验项分类成功!";
                this.BindDirTree();
            }
            else
            {
                divResult.Visible = true;
                OperationResult.Text = "修改检验项分类失败!";
            }
        }
        catch (Exception ex)
        {
            divResult.Visible = true;
            OperationResult.Text = "修改检验项分类失败!";
            log.Error(ex);
        }
    }

    protected void btnItemCreateSave_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(txtItemAddName.Text.Trim()))
        {
            divResult.Visible = true;
            OperationResult.Text = "请输入完整信息!检验项名称不能为空!";
            return;
        }
        if (string.IsNullOrEmpty(txtItemAddPrice.Text.Trim()))
        {
            divResult.Visible = true;
            OperationResult.Text = "请输入完整信息!检验价格不能为空!";
            return;
        }
        try
        {
            decimal.Parse(txtItemAddPrice.Text.Trim());
        }
        catch(Exception ex)
        {
            divResult.Visible = true;
            OperationResult.Text = "请输入完整信息!检验价格不正确!";
            log.Error(ex);
            return;
        }

        try
        {
            MoTestCatalog modCatalog = new MoTestCatalog();
            MoTestItem modItem = new MoTestItem();

            modCatalog.CreateTime = DateTime.Now;
            modCatalog.ParentCtgId = testCatalogTreeView.SelectedValue;
            modCatalog.Rem = txtItemAddMemo.Text;
            modCatalog.TcFlag = "I";
            modCatalog.TestCtgId = SequenceKeys.GenerateTestCatalogID();
            modCatalog.TestCtgName = txtItemAddName.Text;
            modCatalog.UpdateTime = modCatalog.CreateTime;

            modItem.Ability_Status = int.Parse(ddlItemAddStatus.SelectedValue);
            modItem.Dept_Id = ddlItemAddDept.SelectedValue;
            modItem.Item_Code = modCatalog.TestCtgId;
            modItem.Price = decimal.Parse(txtItemAddPrice.Text);
            modItem.Test_Parameters = txtItemAddParameter.Text;

            if (daItem.AddTestItem(modCatalog, modItem))
            {
                divResult.Visible = true;
                OperationResult.Text = "检验项创建成功!";
                this.BindItemsDgv(testCatalogTreeView.SelectedValue,true);
            }
            else
            {
                divResult.Visible = true;
                OperationResult.Text = "检验项创建失败!";
            }
        }
        catch (Exception ex)
        {
            divResult.Visible = true;
            OperationResult.Text = "检验项创建发生异常!";
            log.Error(ex);
        }
    }

    protected void btnItemEidtSave_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(txtItemEidtName.Text.Trim()))
        {
            divResult.Visible = true;
            OperationResult.Text = "请输入完整信息!检验项名称不能为空!";
            return;
        }
        if (string.IsNullOrEmpty(txtItemEidtPrice.Text.Trim()))
        {
            divResult.Visible = true;
            OperationResult.Text = "请输入完整信息!检验价格不能为空!";
            return;
        }
        try
        {
            decimal.Parse(txtItemEidtPrice.Text.Trim());
        }
        catch (Exception ex)
        {
            divResult.Visible = true;
            OperationResult.Text = "请输入完整信息!检验价格不正确!";
            log.Error(ex);
            return;
        }

        try
        {
            MoTestCatalog modCatalog = daCatalog.GetEntity(labItemEditID.Text);
            MoTestItem modItem = daItem.GetEntity(labItemEditID.Text);

            modCatalog.TestCtgName = txtItemEidtName.Text;
            modCatalog.Rem = txtItemEidtMemo.Text;
            modItem.Price = decimal.Parse(txtItemEidtPrice.Text);
            modItem.Test_Parameters = txtItemEidtParameter.Text;
            modItem.Dept_Id = ddlItemEidtDept.SelectedValue;
            modItem.Ability_Status =int.Parse( ddlItemEidtStatus.SelectedValue);

            if (daItem.UpdateTestItem(modCatalog, modItem))
            {
                divResult.Visible = true;
                OperationResult.Text = "检验项修改成功!";
                this.BindItemsDgv(testCatalogTreeView.SelectedValue,false);
            }
            else
            {
                divResult.Visible = true;
                OperationResult.Text = "检验项修改失败!";
            }
        }
        catch (Exception ex)
        {
            divResult.Visible = true;
            OperationResult.Text = "检验项修改发生异常!";
            log.Error(ex);
        }
    }

    protected void btnCreateTemplate_Click(object sender, EventArgs e)
    {
        DaFileTemplate daTemplate = new DaFileTemplate();
        MoFileTemplate mod = new MoFileTemplate();

        mod.Create_Time = DateTime.Now;
        mod.Ft_Id = SequenceKeys.GenerateFileTemplatePairID();
        mod.Item_Code = btnCreateTemplate.CommandName;
        try
        {
            daTemplate.Add(mod);

            BindTemplateRepeater(btnCreateTemplate.CommandName);
        }
        catch (Exception ex)
        {
            divResult.Visible = true;
            OperationResult.Text = "创建模板对失败！";
            log.Error(ex);
        }
    }

    protected void RepTemplate_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (string.IsNullOrEmpty(e.CommandName))
        {
            return;
        }
        try
        {
            if (daItem.DeleteItemTemplate(e.CommandName))
            {
                BindTemplateRepeater(btnCreateTemplate.CommandName);
            }
            else
            {
                divResult.Visible = true;
                OperationResult.Text = "删除模板对失败！";
            }
        }
        catch (Exception ex)
        {
            divResult.Visible = true;
            OperationResult.Text = "删除模板对失败！";
            log.Error(ex);
        }
    }

    protected void BindTemplateRepeater(string itemid)
    {
        RepTemplate.DataSource = daItem.QueryFileTemplate(itemid);
        RepTemplate.DataBind();
    }
    protected void btnUploadParFile_Click(object sender, EventArgs e)
    {
        if (ViewState["ITEMID"] != null)
        {
            BindTemplateRepeater(ViewState["ITEMID"].ToString());
        }
    }
}
